package com.tacc.tyun.controller;

import com.tacc.tyun.model.info.ReturnInfo;
import com.tacc.tyun.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author yu sheng qiang
 * @create 2017-03-27 11:20
 **/
@Controller
@RequestMapping(value = "/file")
@PropertySource("classpath:env.properties")
public class FileController {

    private static Logger log= LoggerFactory.getLogger(FileController.class);

   // @Autowired
   // private ProProperties proProperties;
    @Value("${image.imageurl}")
    private String imageUrl;

    @Value("${image.baseUploadURL}")
    private String baseUploadURL;

    @Value("${image.baseVisitURL}")
    private String baseVisitURL;

    /**
     * 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file" name="myfiles"/>
     * 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
     */
    @RequestMapping(value="/fileUpload")
    @ResponseBody
    public ReturnInfo addUser(@RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String realPath = request.getSession().getServletContext().getRealPath(imageUrl);//这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断路径是否存在,不存在会自动创建
        response.setContentType("text/plain; charset=UTF-8"); //设置响应给前台内容的数据格式
        String newFileName = null;
        for(MultipartFile myfile : myfiles){
            if(myfile.isEmpty()){
                log.info("请选择文件后上传");
                return new ReturnInfo(2,"请选择文件后上传");
            }else{
                newFileName = DateUtil.DateToStr(new Date(),DateUtil.DATE_TIME_PATTERN_1)+ BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT,6)+"."+BaseUtil.acceptFileType(myfile.getOriginalFilename());
                log.info("文件名: " + newFileName+";文件原名: " + myfile.getOriginalFilename()+";文件名称: " + myfile.getName()+";文件长度: " + myfile.getSize()+";文件类型: " + myfile.getContentType());
                try {
                    //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    //此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, newFileName));
                } catch (IOException e) {
                    log.info("文件[" + newFileName + "]上传失败,堆栈轨迹如下");
                    e.printStackTrace();
                    return new ReturnInfo(2,"文件上传失败，请重试！！");
                }
            }
        }
        String url=request.getContextPath() + "/upload/" + newFileName;
        return new ReturnInfo(1,url);
    }

    /**
     * 压缩，保存时按配置文件加入查看下载
     * 利用_NEW来显示
     */
    @RequestMapping(value="/fileUploadCompress")
    public String uplodCompress(@RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //String realPath = request.getSession().getServletContext().getRealPath(ProProperties.getInstance().getPictureURL());//这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断路径是否存在,不存在会自动创建
        response.setContentType("text/plain; charset=UTF-8"); //设置响应给前台内容的数据格式
        PrintWriter out = response.getWriter();//设置响应给前台内容的PrintWriter对象
        String newFileName = null;
        String sizeFileName = null;
        for(MultipartFile myfile : myfiles){
            if(myfile.isEmpty()){
                log.info("请选择文件后上传");
                out.print("请选择文件后上传");
                out.flush();
                return null;
            }else{
                //newFileName = DateUtil.DateToStr(new Date(),DateUtil.DATE_TIME_PATTERN_1)+ BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT,6)+"."+BaseUtil.acceptFileType(myfile.getOriginalFilename());
                newFileName= FilePathUtil.getFilePath(myfile.getOriginalFilename());
                log.info("文件名: " + newFileName+";文件原名: " + myfile.getOriginalFilename()+";文件名称: " + myfile.getName()+";文件长度: " + myfile.getSize()+";文件类型: " + myfile.getContentType());
                try {
                    File targetFile = new File(newFileName);
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(),targetFile);
                    //压缩后上传并删除原文件
                    //此时targetFile应该就是file流

                    sizeFileName = ImangeUtil.createNewImage(targetFile, 1, 360, 200);
                    //删除源文件
                    //targetFile.delete();

                } catch (Exception e) {
                    log.info("文件[" + newFileName + "]上传失败,堆栈轨迹如下");
                    e.printStackTrace();
                    out.print("文件上传失败，请重试！！");
                    out.flush();
                    return null;
                }
            }
        }

        // 生成图片的绝对引用地址
        String picUrl = StringUtils.replace(StringUtils.substringAfter(sizeFileName, baseUploadURL),
                "\\", "/");
        out.print("0`" + baseVisitURL+picUrl);
        out.flush();
        return null;
    }

}
